﻿<template>
  <div class="login-container">
    <!-- 背景特效 -->
    <div class="bg-effects">
      <div class="floating-particles">
        <div v-for="i in 20" :key="i" class="particle" :style="getParticleStyle(i)"></div>
      </div>
      <div class="grid-lines"></div>
      <div class="glow-orbs">
        <div class="glow-orb orb-1"></div>
        <div class="glow-orb orb-2"></div>
        <div class="glow-orb orb-3"></div>
      </div>
    </div>

    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 卡片头部 -->
      <div class="card-header">
        <div class="logo-section">
          <div class="logo-text-container">
            <h1 class="logo-text">数溪汇流</h1>
            <p class="logo-subtitle">DATA CONVERGENCE PLATFORM</p>
          </div>
        </div>
      </div>

      <!-- 登录表单 -->
      <div class="card-body">
        <div class="welcome-section">
          <h2 class="welcome-title">欢迎回来</h2>
          <p class="welcome-subtitle">请登录您的账户继续操作</p>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          size="large"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              class="sci-fi-input"
              :prefix-icon="User"
            >
              <template #prefix>
                <i class="input-icon">👤</i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              class="sci-fi-input"
              :prefix-icon="Lock"
              show-password
            >
              <template #prefix>
                <i class="input-icon">🔒</i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
            >
              <span v-if="!loading">
                登录系统
              </span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 系统状态 -->
        <div class="system-status">
          <div class="status-item">
            <div class="status-indicator">
              <div class="status-dot online"></div>
              <span class="status-text">系统在线</span>
            </div>
          </div>
          <div class="version">v2.1.0</div>
        </div>
      </div>
    </div>

    <!-- 底部信息 -->
    <div class="footer-info">
      <div class="tech-stack">
        <span class="tech-item">⚡ 高性能计算</span>
        <span class="tech-item">🔐 安全加密</span>
        <span class="tech-item">🌐 分布式架构</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度在 6 到 30 个字符', trigger: 'blur' }
  ]
}

// 粒子样式
const getParticleStyle = (index) => {
  const size = Math.random() * 4 + 1
  const duration = Math.random() * 20 + 10
  const delay = Math.random() * 5
  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${Math.random() * 100}%`,
    animationDuration: `${duration}s`,
    animationDelay: `${delay}s`
  }
}

// 登录方法
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    loading.value = true

    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: loginForm.username,
        password: loginForm.password
      })
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`请求失败: ${response.status} - ${errorText}`)
    }

    const result = await response.json()
    console.log('API响应:', result)

    // 处理嵌套的数据结构
    if (result.code === 200 && result.data) {
      const innerData = result.data
      
      // 检查内层的code（如果有的话）
      if (innerData.code && innerData.code !== 200) {
        throw new Error(innerData.message || '登录失败')
      }
      
      const token = innerData.token
      const userInfo = innerData.userInfo
      
      if (!token) {
        throw new Error('未获取到认证令牌')
      }
      
      // 存储认证信息
      localStorage.setItem('auth_token', token)
      if (userInfo) {
        localStorage.setItem('user_info', JSON.stringify(userInfo))
      }
      
      // 设置全局请求头
      setAuthToken(token)
      
      ElMessage.success(innerData.message || '登录成功')
      
      // 跳转到主页面
      setTimeout(() => {
        router.push('/')
      }, 1000)
    } else {
      throw new Error(result.message || '登录失败')
    }
    
  } catch (error) {
    console.error('Login failed:', error)
    ElMessage.error('登录失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 设置认证 token 到请求头
const setAuthToken = (token) => {
  // 设置全局 fetch 拦截器
  const originalFetch = window.fetch
  window.fetch = (...args) => {
    const [url, options = {}] = args
    const newOptions = {
      ...options,
      headers: {
        ...options.headers,
        'Authorization': `Bearer ${token}`
      }
    }
    return originalFetch(url, newOptions)
  }
}

// 检查是否已登录
const checkLoginStatus = () => {
  const token = localStorage.getItem('auth_token')
  if (token) {
    setAuthToken(token)
    router.push('/')
  }
}

onMounted(() => {
  checkLoginStatus()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #0c0e1a 0%, #1a1f35 50%, #0f1220 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  font-family: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 背景特效 */
.bg-effects {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.floating-particles {
  position: absolute;
  width: 100%;
  height: 100%;
}

.particle {
  position: absolute;
  background: linear-gradient(45deg, #00f2fe, #9d50bb);
  border-radius: 50%;
  opacity: 0.3;
  animation: float 20s infinite linear;
}

@keyframes float {
  0% {
    transform: translateY(100vh) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 0.3;
  }
  90% {
    opacity: 0.3;
  }
  100% {
    transform: translateY(-100px) rotate(360deg);
    opacity: 0;
  }
}

.grid-lines {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: 
    linear-gradient(rgba(79, 172, 254, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(79, 172, 254, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: gridMove 20s linear infinite;
}

@keyframes gridMove {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(50px, 50px);
  }
}

.glow-orbs {
  position: absolute;
  width: 100%;
  height: 100%;
}

.glow-orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(60px);
  opacity: 0.1;
}

.orb-1 {
  width: 300px;
  height: 300px;
  background: #00f2fe;
  top: 10%;
  left: 10%;
  animation: orbFloat1 15s ease-in-out infinite;
}

.orb-2 {
  width: 400px;
  height: 400px;
  background: #9d50bb;
  bottom: 10%;
  right: 10%;
  animation: orbFloat2 20s ease-in-out infinite;
}

.orb-3 {
  width: 200px;
  height: 200px;
  background: #00ff88;
  top: 50%;
  left: 80%;
  animation: orbFloat3 12s ease-in-out infinite;
}

@keyframes orbFloat1 {
  0%, 100% { transform: translate(0, 0) scale(1); }
  50% { transform: translate(50px, -30px) scale(1.1); }
}

@keyframes orbFloat2 {
  0%, 100% { transform: translate(0, 0) scale(1); }
  50% { transform: translate(-30px, 40px) scale(1.05); }
}

@keyframes orbFloat3 {
  0%, 100% { transform: translate(0, 0) scale(1); }
  50% { transform: translate(-20px, -20px) scale(1.2); }
}

/* 登录卡片 */
.login-card {
  background: rgba(16, 18, 27, 0.85);
  backdrop-filter: blur(25px);
  border: 1px solid rgba(79, 172, 254, 0.25);
  border-radius: 20px;
  padding: 48px 40px;
  width: 440px;
  position: relative;
  z-index: 10;
  box-shadow: 
    0 25px 50px rgba(0, 0, 0, 0.4),
    0 0 120px rgba(79, 172, 254, 0.15);
  animation: cardAppear 0.8s ease-out;
}

@keyframes cardAppear {
  0% {
    opacity: 0;
    transform: translateY(30px) scale(0.95);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.card-header {
  text-align: center;
  margin-bottom: 48px;
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-text-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.logo-text {
  font-size: 2.2em;
  font-weight: 700;
  margin: 0;
  background: linear-gradient(135deg, #00f2fe 0%, #9d50bb 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: -0.5px;
  line-height: 1.1;
}

.logo-subtitle {
  font-size: 0.75em;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.5);
  margin: 0;
  letter-spacing: 1.5px;
  text-transform: uppercase;
}

/* 卡片主体 */
.card-body {
  position: relative;
}

.welcome-section {
  text-align: center;
  margin-bottom: 36px;
}

.welcome-title {
  color: #fff;
  font-size: 1.6em;
  font-weight: 600;
  margin: 0 0 8px 0;
  letter-spacing: -0.3px;
  line-height: 1.2;
}

.welcome-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.95em;
  margin: 0;
  font-weight: 400;
  line-height: 1.4;
}

/* 登录表单 */
.login-form {
  margin-bottom: 32px;
}

:deep(.sci-fi-input .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.06) !important;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(79, 172, 254, 0.3) !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15) !important;
  transition: all 0.3s ease;
}

:deep(.sci-fi-input .el-input__wrapper:hover) {
  border-color: rgba(79, 172, 254, 0.5) !important;
  box-shadow: 0 6px 25px rgba(79, 172, 254, 0.2) !important;
}

:deep(.sci-fi-input .el-input__wrapper.is-focus) {
  border-color: #00f2fe !important;
  box-shadow: 0 8px 30px rgba(0, 242, 254, 0.25) !important;
}

:deep(.sci-fi-input .el-input__inner) {
  color: #fff !important;
  background: transparent !important;
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 0.2px;
}

:deep(.sci-fi-input .el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5) !important;
  font-weight: 400;
}

.input-icon {
  font-size: 16px;
  margin-right: 8px;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 52px;
  background: linear-gradient(135deg, #00f2fe 0%, #4facfe 50%, #9d50bb 100%) !important;
  border: none !important;
  border-radius: 12px !important;
  color: #fff !important;
  font-weight: 600;
  font-size: 16px;
  letter-spacing: 0.3px;
  transition: all 0.3s ease !important;
  box-shadow: 0 6px 20px rgba(79, 172, 254, 0.4) !important;
  position: relative;
  overflow: hidden;
}

.login-btn:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 10px 30px rgba(79, 172, 254, 0.6) !important;
}

.login-btn:active {
  transform: translateY(0) !important;
}

.login-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.login-btn:hover::before {
  left: 100%;
}

/* 系统状态 */
.system-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 24px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 16px;
  background: rgba(0, 255, 136, 0.1);
  border-radius: 16px;
  border: 1px solid rgba(0, 255, 136, 0.3);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: pulse 2s infinite;
  background: #00ff88;
}

.status-text {
  font-size: 0.85em;
  font-weight: 500;
  color: #00ff88;
  letter-spacing: 0.2px;
}

.version {
  font-size: 0.85em;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.5);
  letter-spacing: 0.2px;
}

/* 底部信息 */
.footer-info {
  position: absolute;
  bottom: 30px;
  left: 0;
  right: 0;
  text-align: center;
  z-index: 10;
}

.tech-stack {
  display: flex;
  justify-content: center;
  gap: 32px;
}

.tech-item {
  font-size: 0.9em;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.6);
  letter-spacing: 0.3px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    width: 90%;
    padding: 32px 24px;
    margin: 20px;
  }
  
  .logo-text {
    font-size: 1.9em;
  }
  
  .tech-stack {
    flex-direction: column;
    gap: 12px;
  }
  
  .logo-text-container {
    align-items: center;
  }
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>